// Copyright (c) 2011 Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "crashdetector.h"

#ifdef WIN32
    #include <Windows.h>
#else
    #include <signal.h>
#endif

#ifdef WIN32

static LPTOP_LEVEL_EXCEPTION_FILTER previousExceptionFilter;

static LONG WINAPI HandleException(LPEXCEPTION_POINTERS exc) 
{
    CrashHandler ch = CrashDetector::GetInstance()->GetCrashHandler();
    if (ch != 0) {
        ch();
    }
    return EXCEPTION_EXECUTE_HANDLER;
}

#else

static void (*previousSignalHandler)(int);

static void HandleSIGSEGV(int sig) 
{
    CrashHandler ch = CrashDetector::GetInstance()->GetCrashHandler();
    if (ch != 0) {
        ch();
    }
    signal(sig, SIG_DFL);
}

#endif

static void InstallGlobalHandler() {
#ifdef WIN32
    previousExceptionFilter = SetUnhandledExceptionFilter(HandleException);
#else
    previousSignalHandler = signal(SIGSEGV, HandleSIGSEGV);
#endif
}

static void RemoveGlobalHandler() {
#ifdef WIN32
    SetUnhandledExceptionFilter(previousExceptionFilter);
#else
    signal(SIGSEGV, previousSignalHandler);
#endif
}

CrashDetector::CrashDetector() 
    : handler_(0)
{
}

CrashHandler CrashDetector::GetCrashHandler() const {
    return handler_;
}

void CrashDetector::SetCrashHandler(CrashHandler handler) {
    handler_ = handler;
    if (handler != 0) {
        InstallGlobalHandler();
    } else {
        RemoveGlobalHandler();
    }
}
